package com.im.tcp.server;


import com.im.tcp.MQFactory;
import com.im.tcp.feign.RpcServer;
import com.im.tcp.publisher.MqChartMsgProduce;
import com.lld.im.common.config.ImTcpConfig;
import com.im.tcp.receiver.MQMsgReceiver;
import com.im.tcp.receiver.UserLoginMsgReceiver;
import com.im.tcp.register.ZKKit;
import com.im.tcp.register.ZKRegister;
import com.rabbitmq.client.ConnectionFactory;
import feign.Feign;
import feign.jackson.JacksonDecoder;
import feign.jackson.JacksonEncoder;
import lombok.extern.slf4j.Slf4j;
import org.I0Itec.zkclient.ZkClient;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;

@Slf4j
@Component
public class MainBootStartBean {



    public MainBootStartBean(ImTcpConfig imTcpConfig, ConnectionFactory connectionFactory, RedissonClient redissonClient) {
        try {
            //初始化feign客户端 指定feign客户端的host以及port
            RpcServer rpcServer = new Feign.Builder()
                    .encoder(new JacksonEncoder())
                    .decoder(new JacksonDecoder())
                    .target(RpcServer.class, imTcpConfig.getMsgRpcUrl());
            String hostAddress = InetAddress.getLocalHost().getHostAddress();
            //初始化netty的tcp/websocket连接
            new NettyServer(imTcpConfig,redissonClient, rpcServer).start(hostAddress);
            new WebSocketServer(imTcpConfig,redissonClient, rpcServer).start(hostAddress);
            //初始化mq消息发送与接收
            MQFactory.init(connectionFactory);
            MQMsgReceiver.init(imTcpConfig.getBrokerId());
            MqChartMsgProduce.init();
            //初始化注册中心 zookeeper
            initZK(imTcpConfig,hostAddress);
            //初始化用户登录消息接收器
            UserLoginMsgReceiver.init(imTcpConfig.getLoginMode(),redissonClient);
        } catch (UnknownHostException e) {
            log.error("初始化出现异常! {}",e.getMessage());
        }
    }

    private void initZK(ImTcpConfig imTcpConfig,String hostAddress) throws UnknownHostException {
        /* 这里的address为 ip:port  */
        ZkClient zkClient = new ZkClient(imTcpConfig.getZkConfig().getAddress(),
                imTcpConfig.getZkConfig().getConnectOutTime());
        ZKKit zkKit = new ZKKit(zkClient, imTcpConfig.getBrokerId());

        ZKRegister zkRegister = new ZKRegister(hostAddress, imTcpConfig, zkKit);
        new Thread(zkRegister).start();
    }
}
